﻿using System.Collections.Generic;
using Assets.Scripts.Net;
using Assets.Scripts.Net.Data;
using Assets.Scripts.Net.Data.Model;
using Assets.Scripts.Net.Loader;
using Assets.Scripts.Tool;
using UnityEngine;
using UnityEngine.UI;


namespace Assets.Scripts.UI.Panel
{
    public class LoginPanel:UIBase<LoginPanel>
    {
        private int loginSuccessTime = 0;

        #region 组件

        public InputField UserNameField;
        public InputField PassWordField;
        public Button LoginButton;
        public Button LoginTestButton;
        public Button ExitButton;
        public Text Version;

        #endregion

        protected override UIType UIType
        {
            get { return UIType.Panel;}
        }

        protected override void InitOnAwake()
        {
            AutoFindComponent(transform,true);
            LoginButton.onClick.AddListener(OnLoginButtonClick);
            ExitButton.onClick.AddListener(OnExitButtonClick);
            UserNameField.text = PlayerPrefs.GetString("Account");
            Version.text = "Version:" + Application.version;
#if UNITY_EDITOR
            PassWordField.text = PlayerPrefs.GetString("Password");
#endif
            LoginTestButton.onClick.AddListener(()=> { StartCoroutine(LoginTest()); });
            LoginTestButton.gameObject.SetActive(false);
#if TEST
            LoginTestButton.gameObject.SetActive(true);            
#endif
        }

        /// <summary>
        /// 登入(压力测试)
        /// </summary>
        private System.Collections.IEnumerator LoginTest() {
            loginSuccessTime = 0;
            for (int j = 0; j < 5; j++)
            {                
                for (int i = 0; i < 200; i++)
                {
                    if (string.IsNullOrEmpty(UserNameField.text) || string.IsNullOrEmpty(PassWordField.text))
                    {
                        UIManager._Instance.ShowTipInfo("用户名或密码不能为空！！！");
                        yield break;
                    }
                    string account = UserNameField.text;
                    string md5psd = Md5Encript.GetMd5HashStr(PassWordField.text);
                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    dict.Add("account", account);
                    dict.Add("password", md5psd);
                    dict.Add("type", 1);
                    int temp = i;
                    NetManager.Instance.SendRequest(RequestType.Login, dict, () =>
                    {
                        loginSuccessTime++;
                        Debug.LogWarning("登入成功:" + loginSuccessTime);
                    },
                    dicts => {
                        Debug.LogError("登入失败:" + (temp + i));
                    });
                }
                yield return new WaitForSeconds(1.0f);
            }              
        }

        /// <summary>
        /// 登入按钮的点击事件
        /// </summary>
        private void OnLoginButtonClick()
        {
            if (string.IsNullOrEmpty(UserNameField.text) || string.IsNullOrEmpty(PassWordField.text))
            {
                UIManager._Instance.ShowTipInfo("用户名或密码不能为空！！！");
                return;
            }
            string account = UserNameField.text;
            string md5psd = Md5Encript.GetMd5HashStr(PassWordField.text);
            Dictionary<string,object>dict=new Dictionary<string, object>();
            dict.Add("account",account);
            dict.Add("password",md5psd);
            dict.Add("type",1);
            NetManager.Instance.SendRequest(RequestType.Login, dict, () =>
            {              
                //todo 得到登入的数据
                StudentInfo info = NetReaderFactory.Instance().GetInfoByType<StudentInfo>() as StudentInfo;
                if (info != null && info.HaveExam)
                {
                    //向服务器发送请求考试问题的请求
                    EnterExam();
                }
                else
                {
                    CreatePanel(PanelType.MainPanel);                    
                }
                PlayerPrefs.SetString("Account", UserNameField.text);
#if UNITY_EDITOR
                PlayerPrefs.SetString("Password", PassWordField.text);
#endif
                Exit();//将LoginPanel退出
            });
        }


        private void EnterExam()
        {
            //考试的信息变化较大，暂时不考虑，比较本地信息
            Dictionary<string, object> dict = NetManager.Instance.GetDict();
            NetManager.Instance.SendRequest(RequestType.EnterExamination, dict, () =>
            {
                if (NetReaderFactory.Instance().NetResUrls.Count > 0)//有需要加载的资源
                {
                    LoadingPanel loadingPanel = CreatePanel(PanelType.LoadingPanel).GetComponent<LoadingPanel>();
                    loadingPanel.Init(LoadingType.WWWLoading);
                    Global.Global.Instance.StartCoroutine(WWWLoadManager.Instance()
                        .DownLoadSaveResource(NetReaderFactory.Instance().NetResUrls, () =>
                        {
                            Exit("LoadingPanel(Clone)");
                            ExamRulePanel panel = CreatePanel(PanelType.ExamRulePanel).GetComponent<ExamRulePanel>();
                            ExamInfo info = NetReaderFactory.Instance().GetInfoByType<ExamInfo>() as ExamInfo;
                            panel.Init(info);
                        }));
                }
                else//没有需要加载的资源
                {
                    ExamRulePanel panel = CreatePanel(PanelType.ExamRulePanel).GetComponent<ExamRulePanel>();
                    ExamInfo info = NetReaderFactory.Instance().GetInfoByType<ExamInfo>() as ExamInfo;
                    //Debug.Log(info.examname);
                    //Debug.Log(info.countdown);
                    panel.Init(info);
                }
            }); 
        }

        /// <summary>
        /// 退出按钮的点击事件
        /// </summary>
        private void OnExitButtonClick()
        {
            TipPanel panel = CreatePanel(PanelType.TipPanel).GetComponent<TipPanel>();
            panel.Init("确认退出程序吗？", Application.Quit);
        }

        protected override void Update()
        {
            if (Input.GetKeyDown(KeyCode.KeypadEnter)||Input.GetKeyDown(KeyCode.Return))
            {
                Debug.Log("enter点击事件，，，，，");
                LoginButton.onClick.Invoke();
            }
        }
    }
}
